package com.hqyj.seatastock.service.impl;

import com.hqyj.seatastock.domain.Stock;
import com.hqyj.seatastock.mapper.StockMapper;
import com.hqyj.seatastock.service.StockService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.Optional;

@Service
public class StockServiceImpl implements StockService {
    @Resource
    private StockMapper stockMapper;

    @Override
    public void deduct(int productId, int number) {
        Optional<Stock> byId = Optional.ofNullable(stockMapper.selectById(productId));

        if(byId.isPresent()) {
            Stock storage = byId.get();
            if(storage.getNumber() >= number) {
                // 减库存
                storage.setNumber(storage.getNumber() - number);
                //stockMapper.insert(storage);
                stockMapper.updateById(storage);
            }
            else {
                throw new RuntimeException("该商品库存不足！");
            }
        }
        else {
            throw new RuntimeException("该商品不存在！");
        }
    }
}
